/*
 *  Gurr - A multiprotocol chat client for Android
 *  Copyright (C) 2011 Malte Aschermann, Wilfried Ramaker
 *  
 *  This file is part of Gurr.
 *  
 *  Gurr is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *  
 *  Gurr is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *  
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with Gurr.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.masc.gurr.view.activities;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.kano.joscar.net.ClientConn;
import net.kano.joscar.net.ClientConn.State;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.masc.gurr.Controller;
import com.masc.gurr.R;
import com.masc.gurr.model.Contact;
import com.masc.gurr.model.Group;
import com.masc.gurr.model.Message;
import com.masc.gurr.model.ProtocolType;
import com.masc.gurr.model.Session;
import com.masc.gurr.net.otr.OTRDriver;

public class ChatWindowActivity extends Activity implements View.OnClickListener {
	private List<Message> itemList;
	private ListView listView;
	private Button sendButton;
	private Button closeButton;
	private TextView uidTW;
	private EditText chatInputET;
	private ChatWindowAdapter chatAdapter;
	private Button otrButton;
	
	
	public ChatWindowActivity(){
		//register activity
		Controller.getInstance().setChatWindowActivity(this);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chat);
		itemList = new ArrayList<Message>();
		
		uidTW = (TextView) findViewById(R.id.userIdTextView);
		String uid = Controller.getInstance().getFocusedUid();
		uidTW.setText(Controller.getInstance().getContacts().getMap().get(uid).getName() + ":" + uid + "\nOTR: " + OTRDriver.getInstance().getOTRState(uid));
		
		sendButton = (Button) findViewById(R.id.btChatSend);
		sendButton.setOnClickListener(this);

		closeButton = (Button) findViewById(R.id.btCloseChat);
		closeButton.setOnClickListener(this);
		
		otrButton = (Button) findViewById(R.id.btOTR);
		otrButton.setOnClickListener(this);

		getItemList();
		listView = (ListView) findViewById(R.id.chatListView);
		listView.setAdapter(new ChatWindowAdapter());
		
		chatInputET = (EditText) findViewById(R.id.chatInputTextEdit);
		chatInputET.setOnKeyListener( new OnKeyListener() {

			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				if(event.getAction() == KeyEvent.ACTION_DOWN){
					if(keyCode == KeyEvent.KEYCODE_ENTER){
						if(!chatInputET.getText().toString().equals("")){
							Controller.getInstance().addNewChatLine(Controller.getInstance().getFocusedUid(), chatInputET.getText().toString());
							chatInputET.setText("");
							//return true;
						}
						return true;
					}
				}
				return false;
			}
		});
		
		/* if not connected, disable textview+buttons */
		if (Controller.getInstance().getIcq() != null 
			&& Controller.getInstance().getIcq().getState() == ClientConn.STATE_CONNECTED) {
				otrButton.setEnabled(true);
				chatInputET.setEnabled(true);
				sendButton.setEnabled(true);	
		} else {
			otrButton.setEnabled(false);
			chatInputET.setEnabled(false);
			sendButton.setEnabled(false);		
		}
	}

	private void getItemList() {
		//ArrayList<Message> itemList = Controller.getInstance().getMapLocalChatSession().get(Controller.getInstance().getFocusedUid());
		String buddyUin = Controller.getInstance().getFocusedUid();
		//ArrayList<Message> itemList = Controller.getInstance().getCurrentSession(buddyUin, ProtocolType.ICQ).getMessages();
		
		// get all sessions => message list
		ArrayList<Session> lstSessions = Controller.getInstance().getAllSessions(buddyUin, ProtocolType.ICQ);
		//ArrayList<Message> itemList = new ArrayList<Message>();
		itemList.clear();
		for (Session s : lstSessions) {
			if (s.getMessages() != null)
				itemList.addAll(s.getMessages());
		}
	}


	public class ChatWindowAdapter extends ArrayAdapter<Message> {

		ChatWindowAdapter() {
			super(getApplicationContext(), R.layout.chat_window_item, itemList);
			chatAdapter = this;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;

			if (row == null) {
				LayoutInflater inflater = getLayoutInflater();

				row = inflater
						.inflate(R.layout.chat_window_item, parent, false);
			}
				
			TextView labelId = (TextView) row.findViewById(R.id.ID);
			TextView date = (TextView) row.findViewById(R.id.Date);
			TextView content = (TextView) row.findViewById(R.id.Message);
			String sender = "";
			// color label gray if I send the msg
			if(itemList.get(position).getSender().equals(Controller.getInstance().getMyAccount().getUin())){
				sender = Controller.getInstance().getMyAccount().getAlias();
				labelId.setBackgroundColor(Color.DKGRAY);
				date.setBackgroundColor(Color.DKGRAY);
				content.setBackgroundColor(Color.DKGRAY);
			//else the msg is send by a buddy -> color black
			}else{
//				Group g = Controller.getInstance().getContacts();
//				Map<String,Contact> map = Controller.getInstance().getContacts().getMap();
//				String strsender = itemList.get(position).getSender();
				sender = Controller.getInstance().getContacts().getMap().get(itemList.get(position).getSender()).getName();
				labelId.setBackgroundColor(Color.BLACK);
				date.setBackgroundColor(Color.BLACK);
				content.setBackgroundColor(Color.BLACK);
			}
			
			
			labelId.setText(sender);
			date.setText(itemList.get(position).getDate().toGMTString());
			content.setText(itemList.get(position).getContent());
			
			return (row);
		}

	}
	public void onClick(View v) {
		if (v == closeButton) {
			Toast.makeText(this, "close pushed", Toast.LENGTH_SHORT).show();
			//TODO: do something
			this.finish();
					}
		else if( v == sendButton){
			Toast.makeText(this, "send pushed", Toast.LENGTH_SHORT).show();
			//TODO: send via icq, 
			//Update history + Listview
			if(!chatInputET.getText().toString().equals("")){
				Controller.getInstance().addNewChatLine(Controller.getInstance().getFocusedUid(), chatInputET.getText().toString());
				chatInputET.setText("");
			}
		}
		else if(v == otrButton){
			//start OTR session
			String uin = Controller.getInstance().getFocusedUid();
			try {
				OTRDriver.getInstance().getOTRSession(Controller.getInstance().getMyAccount().getAlias(),OTRDriver.PROTOCOL_ID_ICQ, uin);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			uidTW.setText(Controller.getInstance().getContacts().getMap().get(uin).getName() + ":" + uin + "\nOTR: " + OTRDriver.getInstance().getOTRState(uin));
		}
	}
	
	public void update() {
		//listView = (ListView) findViewById(R.id.chatListView);
		//listView.setAdapter(new ChatWindowAdapter());
		getItemList();
		chatAdapter.notifyDataSetChanged();
	}

	public ChatWindowAdapter getChatAdapter() {
		return chatAdapter;
	}

	public void setChatAdapter(ChatWindowAdapter chatAdapter) {
		this.chatAdapter = chatAdapter;
	}

	public Button getSendButton() {
		return sendButton;
	}

	public EditText getChatInputET() {
		return chatInputET;
	}

	public Button getOtrButton() {
		return otrButton;
	}
}
